package com.myschool.server.manager.impl;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.myschool.server.dao.GradeDao;
import com.myschool.server.dao.SchoolDao;
import com.myschool.server.dao.support.BaseEntityDaoHibernate;
import com.myschool.server.manager.BaseManager;
import com.myschool.server.manager.GradeManager;
import com.myschool.server.model.Grade;
import com.myschool.server.model.School;
import com.myschool.server.model.Section;
import com.myschool.server.model.Subject;

@Service
@Transactional
public class GradeManagerImpl extends BaseManager<Grade> implements
		GradeManager {

	@Autowired
	private GradeDao gradeDao;

	@Autowired
	private SchoolDao schoolDao;

	@Override
	protected BaseEntityDaoHibernate getDao() {

		return (BaseEntityDaoHibernate) gradeDao;
	}

	public Set<Grade> createSchoolGrades(Long schoolId, Set<Grade> grades) {

		School school = this.schoolDao.get(schoolId);

		for (Grade grade : grades) {

			grade.setSchool(school);
			this.gradeDao.save(grade);
		}

		return grades;
	}

	/**
	 * @return the gradeDao
	 */
	public GradeDao getGradeDao() {
		return gradeDao;
	}

	/**
	 * @param gradeDao
	 *            the gradeDao to set
	 */
	public void setGradeDao(GradeDao gradeDao) {
		this.gradeDao = gradeDao;
	}

	/**
	 * @return the schoolDao
	 */
	public SchoolDao getSchoolDao() {
		return schoolDao;
	}

	/**
	 * @param schoolDao
	 *            the schoolDao to set
	 */
	public void setSchoolDao(SchoolDao schoolDao) {
		this.schoolDao = schoolDao;
	}

	public Grade addSectionsToGrade(Long gradeId, Set<Section> sections) {

		Grade grade = gradeDao.get(gradeId);

		grade.getSections().addAll(sections);

		this.gradeDao.save(grade);
		return grade;
	}

	public Grade addSubjectsToGradeAllSections(Long gradeId,
			Set<Subject> subjects) {

		Grade grade = gradeDao.get(gradeId);

		for (Section section : grade.getSections()) {
			section.getSubjects().addAll(subjects);

		}

		this.gradeDao.save(grade);

		return grade;
	}

	public Set<Grade> retrieveAllGrades(Long schoolId) {
		return this.gradeDao.retrieveAllGradesBySchool(schoolId);

	}
}
